<script setup lang="ts">
import { ref } from 'vue'
import { searchGoodsAPI, tagListAPI } from '@/services/category'
import { onShow, onLoad, onReady } from '@dcloudio/uni-app'
import { getInfoAPI, pointExchangeAPI,
appPointGoodsPageAPI,appPointLogPageAPI,appPointExchangeRecordsPageAPI } from '@/services/points'

import type { IpointsInfo, InvitationInfo, IzyActivitiesItem,
  IpointGoodsPageParam, IpointExchangeRecordsParam, IpointLogParam, 
IZyPointsMallGoodsItem,  ZyPointsExchangeRecordsItem, ZyPointsLogItem
 } from '@/types/points'
import { useCart, useMemberStore } from '@/stores'
const systemInfo = uni.getSystemInfoSync()
const { safeAreaInsets, windowHeight, screenWidth } = systemInfo
const {getUserInfo} = useMemberStore();

// 接收页面参数
const query = defineProps<{
  activeIndex: number
}>()

const activeIndex = ref(query.activeIndex || 0)
const pointTabs = ref([
  { name: '商品兑换', id: 0 },
  { name: '兑换记录', id: 1 },
  { name: '积分规则', id: 2 },
])

const initParams: ISearchPageParams = {
  page: 1,
  limit: 8,
}

const params = ref({...initParams} as ISearchPageParams)

const navPointsRecordHandler = () => {
  uni.navigateTo({
    url: '/pagesMember/points/points-record?balance=' + info.value.totalPoints,
  })
}

const info = ref({} as IpointsInfo)

const noMore = ref(false)
const pointGoodsList = ref<PointGoodsItem[]>([])
const page = ref(1)
const limit = ref(5)
const total = ref(0)
const finish = ref(false)
const keyword = ref(null)

const request = async () => {
  if (finish.value === true) {
    return
  }

  finish.value = true
  let res = null
  if (activeIndex.value === 0) {
    res = await appPointGoodsPageAPI({ ...params.value })
  }
    if (activeIndex.value === 1) {
    res = await appPointExchangeRecordsPageAPI({ ...params.value })
  }
  
  pointGoodsList.value = [...pointGoodsList.value, ...res.data.list]
  total.value = res.data.total
  finish.value = false
}

// 滚动触底
const onScrolltolower = async () => {
  if (finish.value === true) {
    return
  }
  if (pointGoodsList.value.length < total.value) {
    params.value.page = params.value.page + 1
  } else {
    noMore.value = true
    return
  }
  await request()
}

const triggered = ref(false) // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发

const onPulling = (e: any) => {
  if (e.detail.deltaY < 50) return // 防止上滑页面也触发下拉
  triggered.value = true
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = false
}
// 自定义下拉刷新被中止
const onAbort = () => {
  console.error('onAbort')
}

// 自定义下拉刷新被触发
const onRefresh = async () => {
  if (finish.value === true) {
    return
  }
  pointGoodsList.value = []
  params.value.page = initParams.page
  await request()
  triggered.value = false
}

const getInfo = async () => {
  const res = await getInfoAPI({userId: getUserInfo()?.id });
  info.value = res.data;
}

onLoad(async () => {
  getInfo()
  uni.startPullDownRefresh()
  await request()

})
const tabHandler = async (index: number) => {
  activeIndex.value = index
  if ([0,1].includes(index)) {
    params.value.page = initParams.page
    if (index === 1) {
      params.value = {...params.value, status: null, userId: getUserInfo()?.id }
    }
    pointGoodsList.value = []
    await request()
  }
}

const sureHandler = (item: PointGoodsItem) => {
    // 模态弹窗
  uni.showModal({
    content: '会扣减您的积分兑换，确认要兑换吗？',
    success: async (res) => {
      if (res.confirm) {
        await pointExchangeAPI({userId: getUserInfo()?.id, points: item.pointsRequired, goodsId: item.id, quantity: 1 });
        // params.value = {...initParams}
        // pointGoodsList.value = []
        // await request()
        getInfo()
      }
    },
  })
}
</script>

<template>
  <view class="points-page" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="banner">
      <text class="txt">{{info.totalPoints}}</text>
      <view class="btn" @tap="navPointsRecordHandler()"
        ><text>积分明细</text><text class="iconfont icon-jinru"></text
      ></view>
      <text class="info">今日{{info.isSignedToday === 1 ? '已签到': '未签到'}}，可用积分</text>
    </view>

    <view class="tabs">
      <text
        class="item"
        :class="{ active: activeIndex === index }"
        v-for="(item, index) in pointTabs"
        :key="item.id"
        @click="tabHandler(index)"
      >
        {{ item.name }}
      </text>
      <view class="cursor" :style="{ left: activeIndex * 33.33 + '%' }"
        ><view class="inner"></view
      ></view>
    </view>

    <scroll-view 
    v-if="activeIndex === 0" 
    scroll-y 
    :show-scrollbar="false" 
    @scrolltolower="onScrolltolower"
    :refresher-enabled="true"
    :refresher-triggered="triggered"
    :refresher-threshold="100"
    refresher-background="#F5F5F7"
    @refresherpulling="onPulling"
    @refresherrefresh="onRefresh"
    @refresherrestore="onRestore"
    @refresherabort="onAbort"
    enable-back-to-top>
      <view class="goods_item">
        <view class="goods_item_wrap" :key="item" v-for="item in pointGoodsList">
          <image class="goods_image" :src="item.imageUrl"></image>
          <view class="goods_info">
            <text class="goods_name">{{item.name}}</text>
            <view class="goods_price_wrap">
              <text class="goods_price"><text class="num">{{item.pointsRequired}}</text>积分</text>
              <text class="btn" @click="sureHandler(item)">兑换</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <scroll-view 
    v-if="activeIndex === 1" 
    scroll-y 
    :show-scrollbar="false" 
    @scrolltolower="onScrolltolower"
    :refresher-enabled="true"
    :refresher-triggered="triggered"
    :refresher-threshold="100"
    refresher-background="#F5F5F7"
    @refresherpulling="onPulling"
    @refresherrefresh="onRefresh"
    @refresherrestore="onRestore"
    @refresherabort="onAbort"
    enable-back-to-top>
      <view class="goods_item_fen">
        <view class="goods_item_wrap" :key="item" v-for="item in pointGoodsList">
          <image class="goods_image" src="@/static/img/1.png"></image>
          <view class="goods_con">
            <view class="goods_info">
              <text class="name">{{item.goodsName}}</text>
              <text class="price">-{{item.points}}积分</text>
            </view>
            <view class="goods_status">
              <text class="time">{{item.createDate}}</text>
              <text class="status">待发货</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <scroll-view v-if="activeIndex === 2" scroll-y :show-scrollbar="false" enable-back-to-top>
      <view class="goods_item_rule">
        <view class="goods_item_wrap">
          <rich-text :nodes="info.configInfo"></rich-text>
          <!-- <view class="title">积分获取规则</view>
          <view class="con"
            >每日签到：每天签到可获得5积分 邀请好友：每成功邀请1位好友注册可获得50积分
            活动参与：参与平台举办的各类活动可获得相应积分奖励
            商品评价：购买商品后完成评价可获得10积分
          </view>
          <view class="title">积分使用规则</view>
          <view class="con">
            积分可在积分商城兑换各类商品礼品 部分商品可使用积分抵扣部分金额
            积分兑换商品后，将从账户中即时扣除 积分兑换的商品不支持退货退款
          </view>
          <view class="title">积分有效期</view>
          <view class="con"
            >用户获得的积分有效期为获得之日起12个月，过期将自动失效。请注意定期查看积分有效期并及时使用
          </view>

          <view class="tip">
            特别说明：本平台保留对积分规则进行调整和解释的权利。如有疑问，请联系客服。
          </view> -->
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
.points-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f3f4f6;

  .banner {
    display: flex;
    flex-direction: row;
    // align-items: center;
    // justify-content: center;
    height: 224rpx;
    background: linear-gradient(to right, #dc2626 100%, #ef4444 100%);
    color: #fff;
    border-radius: 24rpx;
    margin: 28rpx;
    padding: 32rpx;
    flex-wrap: wrap;
    align-items: center;

    .txt {
      font-size: 80rpx;
      font-weight: bold;
      margin-bottom: 16rpx;
      text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
    }

    .info {
      font-size: 28rpx;
      // opacity: 0.9;
      margin-bottom: 20rpx;
      width: 100%;
    }

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      color: #fff;
      background-color: rgba(255, 255, 255, 0.2);
      border-radius: 60rpx;
      padding: 0 16rpx 0 30rpx;
      margin-left: auto;
      margin-bottom: 20rpx;
      height: 58rpx;
      .iconfont {
        margin-left: 8rpx;
        font-size: 40rpx;
      }
    }
  }

  .tabs {
    display: flex;
    justify-content: space-around;
    line-height: 60rpx;
    margin: 0 10rpx;
    background-color: #fff;
    box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
    position: relative;
    z-index: 9;

    .item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      font-size: 28rpx;
      color: #4b5563;
      font-weight: $font-medium-weight;

      &.active {
        color: #ef4444;
      }
    }

    .cursor {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 33.33%;
      height: 6rpx;
      padding: 0 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .inner {
        height: 100%;
        width: 50%;
        background-color: #ef4444;
      }
      /* 过渡效果 */
      transition: all 0.4s;
    }
  }

  .goods_item {
    background-color: #f3f4f6;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 10rpx;
    padding: 28rpx;
    justify-content: space-between;
    .goods_item_wrap {
      width: calc(50% - 12rpx);
   
      // height: 200rpx;
      // background-color: red;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      border-radius: 24rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      overflow: hidden;
      margin-bottom: 20rpx;

      .goods_image {
        width: 100%;
        height: 280rpx;
        // object-fit: cover;
      }

      .goods_info {
        display: flex;
        flex-direction: column;
        padding: 24rpx;
        gap: 16rpx;
        flex-wrap: wrap;

        .goods_name {
          font-size: 28rpx;
          font-weight: 500;
          color: #1f2937;
          width: 100%;
        }

        .goods_price_wrap {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .goods_price {
            color: #e63946;
            font-size: 20rpx;
            .num {
              font-size: 28rpx;
              font-weight: 600;
              margin-right: 4rpx;
            }
          }

          .btn {
            padding: 0 28rpx;
            background-color: #ef4444;
            color: #fff;
            font-size: 24rpx;
            border-radius: 24rpx;
            font-weight: 500;
            height: 48rpx;
            line-height: 1.9;
          }
        }
      }
    }
  }

  // 商品列表容器
  .goods_item_fen {
    display: flex;
    flex-direction: column;
    padding: 20rpx;
    background-color: #f3f4f6;

    // 单个商品项
    .goods_item_wrap {
      background-color: #fff;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      display: flex;
      margin-bottom: 28rpx;
      padding: 24rpx;

      .goods_image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        margin-right: 24rpx;
      }

      .goods_con {
        flex: 1;
        display: flex;
        flex-direction: column;

        .goods_info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 28rpx;

          .name {
            font-size: 28rpx;
            color: #000000;
            font-weight: 500;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .price {
            font-size: 28rpx;
            color: #ef4444;
            font-weight: 400;
          }
        }

        .goods_status {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .time {
            font-size: 24rpx;
            color: #6b7280;
          }

          .status {
            font-size: 24rpx;
            color: #22c55e;
          }
        }
      }
    }
  }

  .goods_item_rule {
    display: flex;
    flex-direction: column;
    padding: 20rpx;

    .goods_item_wrap {
      // 这里是子元素的样式
      background-color: #ffffff;
      padding: 32rpx;
      border-radius: 24rpx;
      font-size: 24rpx;
      color: #374151;
      strong{
        color: red;
      }

      .title {
        // 标题样式
        font-size: 28rpx;
        color: #000000;
        margin-bottom: 16px;
      }

      .con {
        // 内容区域样式
        font-size: 24rpx;
        color: #374151;
        line-height: 1.5;
        margin-bottom: 16px;
      }

      .tip {
        border: 1px solid #fee2e2;
        background-color: #fef2f2;
        color: #dc2626;
        padding: 20rpx;
        font-size: 24rpx;
        line-height: 1.5;
        margin-bottom: 16px;
      }
    }
  }
}
</style>
